import { Checkbox, Divider } from 'antd';
import React, { useEffect, useState } from 'react';

export type FormProps = {
  menuObj: { label: ''; value: []; children: [{}] };
  childrenArr: [];
  checkAll: boolean;
  index: number;
  setSelectArr: (arr: any[]) => void;
};

const AuthorityForm: React.FC<FormProps> = (props, ref) => {
  useEffect(() => {
    setList(props.checkAll ? props.menuObj.value : []);
    setIndeterminate(false);
    setCheckAll(props.checkAll);
  }, [props.checkAll]);

  const [indeterminate, setIndeterminate] = React.useState(false);
  const [checkAll, setCheckAll] = React.useState(false);
  const [list, setList] = useState([]);

  //全选
  const onCheckAllChange = (e) => {
    setList(e.target.checked ? props.menuObj.value : []);
    setIndeterminate(false);
    setCheckAll(e.target.checked);
  };
  //遍历children
  let plainOptions = props.menuObj.children;
  const onChange = (list) => {
    setList(list);
    setIndeterminate(!!list.length && list.length < plainOptions.length);
    setCheckAll(list.length === plainOptions.length);
  };

  useEffect(() => {
    setList(props.selectValue);
    setIndeterminate(!!props.selectValue.length && props.selectValue.length < plainOptions.length);
    setCheckAll(props.selectValue.length === plainOptions.length);
  }, [props.selectValue]);

  useEffect(() => {
    const obj = props.selectArr.filter((item) => item.label == props.label);
    if (obj.length == 0 && list.length > 0) {
      props.selectArr.push({ label: props.label, labelId: props.labelId, value: list });
    } else {
      for (let i = 0; i < props.selectArr.length; i++) {
        const element = props.selectArr[i];
        if (element.label == props.label) {
          element.value = list;
        }
      }
    }
    // props.selectValue
  }, [list]);
  return (
    <div key={props.index}>
      <Checkbox indeterminate={indeterminate} checked={checkAll} onChange={onCheckAllChange}>
        {props.menuObj.label}
      </Checkbox>
      <br />
      <br />
      <Checkbox.Group options={plainOptions} value={list} onChange={onChange} />
      <Divider />
    </div>
  );
};

export default AuthorityForm;
